package com.reesechou.controller.admin;

import com.reesechou.javabean.Article;
import com.reesechou.javabean.Category;
import com.reesechou.javabean.Tag;
import com.reesechou.service.*;
import org.directwebremoting.util.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by 小星打屁屁 on 2015/3/25.
 * contact me ==>243709758@qq.com
 */
@Controller
@RequestMapping("/jsp/admin/content")
public class ArticleController {
     private static Logger logger = Logger.getLogger(ArticleController.class);

    private static String PAGE_CONTROL = "article_manger";//文章管理
    private static String ART_CREATE = "article_create"; //文章创建

    @Autowired
    private ArticleService articleService ;
    @Autowired
    private CategoryService categoryService ;
    @Autowired
    private TagService tagService;
    @Autowired
    private CategoryArticleService categoryArticleService ;
    @Autowired
    private TagArticleService tagArticleService ;

    /**
     *
     * @param request
     * @param response
     * @param model
     * 在参数列表中直接定义Model，model.addAttribute("p", object);
     * 把参数值放到request类里面去，建议使用
     * @return
     */
    @RequestMapping(value="/article_manger",method = RequestMethod.GET)
    public String articleManger(HttpServletRequest request,HttpServletResponse response ,Model model){
        logger.info("==========文章管理首页！！===============");
        if(articleService==null){
            System.out.println("注入的articleService为空");
        }
        List<Article> articleList = articleService.getAllArticle();
        model.addAttribute("articles", articleList);
        return PAGE_CONTROL ;
    }


    /**
     *
     * 直接在方法的参数列表中来定义Map，这个Map即使ModelAndView里面的Map，
     * 由视图解析器统一处理，统一走ModelAndView的接口，也不建议使用
     */
    @RequestMapping("/toPerson43.do")
    public String toPerson43(Map<String, Object> map) throws Exception {
        map.put("p", new Article());
        return "index";
    }

    @RequestMapping("/art_create")
    public String toArtCreate(HttpServletRequest request,Article article ,Model model){
        logger.info("===========进入文章创建页面toArtCreate()   ===============");
        createReferenceData(article,model);//
        return ART_CREATE ;
    }

    /**
     * 创建文章时，先列举所有的文章分类和tag，供该文章选择
     * @param art
     * @param model
     */
    private void  createReferenceData(Article art ,Model model){
        List<Category> categoryList = categoryService.findAllCategory();
        model.addAttribute("categorys",categoryList);
        //=================================================
        List<Tag> tagList =tagService.getAllTag() ;
        model.addAttribute("tags",tagList);

    }

    @RequestMapping(value = "/art_create",method = RequestMethod.POST)
    public String doArtCreate(HttpServletRequest request,Article article ,Model model){
        logger.info("doArtCreate！==文章入库==");
        //获取 Category 和 tag 的选择结果
        String[] categorys = request.getParameterValues("categorys");
        String[] tags = request.getParameterValues("tags");
        initArticle(article,model);
        createReferenceData(article,model);
        int records = articleService.insert(article);//返回的是插入的记录条数
        int articleId = article.getId();//这里得到的才是真正的文章ID
        categoryArticleService.insertArray(categorys,articleId);
        tagArticleService.insertArray(tags,articleId);


       return ART_CREATE ;
    }

    /**
     * 初始化文章（创建时间，更新时间等等）
     */
    private void initArticle(Article article ,Model model){
        Map<String,Object> map = model.asMap();
        Date submitTime = new Date();
        Date updateTime = new Date();
        Date topTime = new Date();
        String summary = article.getContent().length()>6?article.getContent().substring(0,5)+"...":article.getContent();

        article.setPostTime(submitTime);
        article.setModifyTime(updateTime);
        article.setTopTime(topTime);
        article.setSummary(summary);
        article.setView(0);
        article.setTrash(false);//文章创建的时候 这个 trash 属性都是默认的为 false, 即没有被删除
        article.setArticleType("post");//默认的文章发表类型都为这个 post 类型


    }
}
